import 'dart:convert';

import 'package:casdon/app/config/env/env_provider.dart';
import 'package:casdon/core/encrypt/secure_encryptor.dart';
import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final secureEncryptorProvider = Provider(
  (ref) => {SecureEncryptor(ref.read(environmentProvider))},
);

class EncryptInterceptor extends Interceptor {
  final SecureEncryptor _encryptor;

  EncryptInterceptor(this._encryptor);

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final needEncrypt = options.extra['encrypt'] == true;

    if (needEncrypt && options.data != null) {
      final originalData = options.data;
      final jsonStr = jsonEncode(originalData);
      _encryptor.generateAesKey();

      String? encryptData = _encryptor.encryptData(jsonStr);
      String? encryptedtoken = _encryptor.encryptAesKeyWithRsa();

      if (encryptedtoken == null || encryptData == null) {
        return;
      } else {
        options.headers['encrypt-key'] = encryptedtoken;
        options.data = encryptData;
        // options.headers["Content-Type"] = "text/plain";
        options.headers["isencrypt"] = "true";
      }
    }
    handler.next(options);
  }
}

Provider encryptInterceptorProvider = Provider<EncryptInterceptor>((ref) {
  final encryptor = ref.read(SecureEncryptorProvider);
  final interceptor = EncryptInterceptor(encryptor);
  return interceptor;
});
